<template>
	<!-- #ifdef MP-WEIXIN -->
	<u-popup :show="show" mode="bottom" :round="15" :safeAreaInsetBottom="false">
		<view class="contentBox_e">
			<image :src="appData.logo||'../../static/logo.png'" />
			<view class="appName">
				是否授权【{{appData.name||"小程序名称"}}】
			</view>
			<view class="jurisdiction"> 获取您的公开信息（昵称、头像、地区及性别）</view>
			<view class="df-Jc-sa operation">
				<button @click="getUserInfo">确认授权</button>
				<button @click="show=false">
					暂时不要
				</button>
			</view>
		</view>

	</u-popup>
	<!--  #endif -->

</template>

<script setup>
	//#ifdef MP-WEIXIN
	import { logs, toast } from "@/common/func.js"
	import appData from "@/appConfig.json";
	import apis from "@/apis"
	import { ref, reactive, watch, onMounted } from 'vue'
	const emit = defineEmits(['change'])
	let show = ref(false)
	const bind = () => {
		uni.getStorage({
			key: "bindId",
			success: (bindData) => {
				uni.removeStorageSync('bindId')
				apis['bind']({ scene: bindData.data }).then(res => {
					logs('用户已绑定')
				})
			}
		})
	}
	const getUserInfo = (evt) => {
		uni.getUserProfile({
			desc: '登录授权',
			success: res => {
				const userInfo = JSON.parse(res.rawData)
				let wxuser = {
					nickname: userInfo.nickName,
					avatarUrl: userInfo.avatarUrl,
					sex: userInfo.gender,
					country: userInfo.country,
					province: userInfo.province,
					city: userInfo.city
				}
				//提交用户信息
				apis['updateUser'](wxuser).then(resUpdata => {
					logs('用户信息已更新')
					//保存用户信息
					uni.setStorageSync("userDetail", wxuser)
					toast("授权成功", 1)
					emit("change")
					show.value = false
				})
			}
		})
	}
	const login = () => {
		uni.getStorage({
			key: "token",
			success: () => {
				uni.getStorage({
					key: 'userDetail',
					success: (res) => {
						show.value = false
					},
					fail: () => {
						show.value = true
					}
				})
			},
			fail: () => {
				uni.login({
					timeout: 4000,
					success: loginData => {
						apis['code2session']({
							code: loginData.code
						}).then(tokenData => {
							uni.setStorageSync('token', tokenData.obj.jwt.token)
							bind()
							login()
						})
					}
				})
			}
		})
	}
	defineExpose({
		login
	})
	// #endif
</script>

<style lang="scss" scoped>
	.contentBox_e {
		padding: 50rpx 0 70rpx 0;
		text-align: center;

		image {
			@include boxs(200rpx, 200rpx, 200)
		}

		.appName {
			margin-top: 20rpx;
			@include fz(25, #2979FF, 50);
		}

		.jurisdiction {
			@include fz(25, #000, 50);
			margin-bottom: 20rpx;
		}

		.operation {
			margin: 0 auto;

			button {
				background: rgba(0, 0, 0, 0);
				border: 1rpx solid #c0c4cc;
				@include boxs(264rpx, 70rpx, 10);
				@include fz(26, #606266, 70, true);
			}

			button:nth-child(1) {
				color: #FFFFFF;
				background: #4289FA;
				border: 1rpx solid #4289FA;
			}

			button::after {
				border: none;
			}
		}

	}
</style>
